<template>
  <div class="login-container farmer-login">
    <button class="back-home-btn" @click="goToHome">
      <span class="btn-icon">←</span>
      返回首页
    </button>
    <div class="login-header">
      <h1 class="platform-title">农产品融销一体平台</h1>
      <h2 class="role-title">农户登录</h2>
      <p class="welcome-text">连接农田与市场，助力农产品销售</p>
    </div>

    <div class="login-form-container">
      <div class="form-header">
        <div class="avatar farmer-avatar">
          <i class="icon">👨‍🌾</i>
        </div>
        <h3>农户登录</h3>
      </div>

    <div class="form-section" v-if="!isRegistering">
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="farmer-username">用户名</label>
          <input
            id="farmer-username"
            v-model="form.username"
            type="text"
            placeholder="请输入您的用户名"
            required
          />
        </div>

        <div class="form-group">
          <label for="farmer-password">登录密码</label>
          <input
            id="farmer-password"
            v-model="form.password"
            type="password"
            placeholder="请输入登录密码"
            required
          />
        </div>

        <div class="form-options">
          <label class="remember-me">
            <input type="checkbox" v-model="rememberMe" />
            <span>记住登录状态</span>
          </label>
          <a href="#" class="forgot-password">忘记密码？</a>
        </div>

        <button type="submit" class="login-btn farmer-btn">登录系统</button>

        <div class="register-link">
          <span>还没有账号？</span>
          <a href="#" @click.prevent="switchToRegister">立即注册</a>
        </div>
      </form>
  </div>

  <!-- 注册表单 -->
  <div class="form-section" v-if="isRegistering">
    <form @submit.prevent="handleRegister" class="register-form">
      <div class="form-group" :class="{ error: errors.username }">
      <label for="farmer-username">用户名</label>
      <input
        id="farmer-username"
        v-model="registerForm.username"
        type="text"
        placeholder="请输入用户名"
        required
        @blur="validateField('username')"
      />
      <div v-if="errors.username" class="error-message">{{ errors.username }}</div>
    </div>

      <div class="form-group" :class="{ error: errors.password }">
        <label for="farmer-register-password">设置密码</label>
        <input
          id="farmer-register-password"
          v-model="registerForm.password"
          type="password"
          placeholder="请设置登录密码"
          required
          @blur="validateField('password')"
        />
        <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
      </div>

      <div class="form-group" :class="{ error: errors.realName }">
        <label for="farmer-register-realName">真实姓名</label>
        <input
          id="farmer-register-realName"
          v-model="registerForm.realName"
          type="text"
          placeholder="请输入真实姓名"
          required
          @blur="validateField('realName')"
        />
        <div v-if="errors.realName" class="error-message">{{ errors.realName }}</div>
      </div>

      <div class="form-group" :class="{ error: errors.phone }">
        <label for="farmer-phone">手机号</label>
        <input
          id="farmer-phone"
          v-model="registerForm.phone"
          type="tel"
          placeholder="请输入您的手机号"
          required
          @blur="validateField('phone')"
        />
        <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>
      </div>

      <div class="form-group" :class="{ error: errors.idCard }">
        <label for="farmer-id-card">身份证号</label>
        <input
          id="farmer-id-card"
          v-model="registerForm.idCard"
          type="text"
          placeholder="请输入身份证号"
          required
          @blur="validateField('idCard')"
        />
        <div v-if="errors.idCard" class="error-message">{{ errors.idCard }}</div>
      </div>

      <div class="form-group" :class="{ error: errors.email }">
        <label for="farmer-email">邮箱</label>
        <input
          id="farmer-email"
          v-model="registerForm.email"
          type="email"
          placeholder="请输入邮箱（可选）"
          @blur="validateField('email')"
        />
        <div v-if="errors.email" class="error-message">{{ errors.email }}</div>
      </div>
      
      <button type="submit" class="register-btn">注册账号</button>
      
      <div class="back-to-login">
        <a href="#" @click.prevent="isRegistering = false">返回登录</a>
      </div>
    </form>
  </div>
  </div>

    <div class="login-footer">
      <p>© 2025 农产品融销一体平台 · 农户系统</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { farmerLoginApi, farmerRegisterApi } from '@/api/farmer/login'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const isRegistering = ref(false)
const rememberMe = ref(false)
const form = ref({
  username: '',
  password: '',
  role: 'ROLE_FARMER'
})

const registerForm = ref({
  username: '',
  password: '',
  realName: '',
  phone: '',
  idCard: '',
  email: '',
  targetRole: 'FARMER'
})

// 表单验证错误信息
const errors = ref({})

// 方法
const goToHome = () => {
  router.push('/')
}

//登录
const handleLogin = async() => {
    const result = await farmerLoginApi(form.value);
    if(result.code==200){
    ElMessage.success("登录成功");
    localStorage.setItem('loginUser', JSON.stringify(result.data))
    router.push('/farmer/index')
  }else{
    //提示信息
    ElMessage.error(result.message);
  }
}

// 注册表单验证
const validateRegisterForm = () => {
  const newErrors = {}
  
  // 用户名验证
  if (!registerForm.value.username) {
    newErrors.username = '用户名不能为空'
  } else if (registerForm.value.username.length < 3 || registerForm.value.username.length > 20) {
    newErrors.username = '用户名长度必须在3-20个字符之间'
  } else if (!/^[a-zA-Z0-9_]+$/.test(registerForm.value.username)) {
    newErrors.username = '用户名只能包含字母、数字和下划线'
  }

  // 密码验证
  if (!registerForm.value.password) {
    newErrors.password = '密码不能为空'
  } else if (registerForm.value.password.length < 6 || registerForm.value.password.length > 20) {
    newErrors.password = '密码长度必须在6-20个字符之间'
  }

  // 真实姓名验证
  if (!registerForm.value.realName) {
    newErrors.realName = '真实姓名不能为空'
  } else if (registerForm.value.realName.length > 50) {
    newErrors.realName = '真实姓名长度不能超过50个字符'
  }

  // 手机号验证
  if (!registerForm.value.phone) {
    newErrors.phone = '手机号不能为空'
  } else if (!/^1[3-9]\d{9}$/.test(registerForm.value.phone)) {
    newErrors.phone = '手机号格式不正确'
  }

  // 身份证号验证
  if (!registerForm.value.idCard) {
    newErrors.idCard = '身份证号不能为空'
  } else if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/.test(registerForm.value.idCard)) {
    newErrors.idCard = '身份证号格式不正确'
  }

  // 邮箱验证
  if (registerForm.value.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.value.email)) {
    newErrors.email = '邮箱格式不正确'
  }

  errors.value = newErrors
  return Object.keys(newErrors).length === 0
}

// 为每个字段添加单独的验证函数
const validateField = (field) => {
  const newErrors = { ...errors.value }
  const value = registerForm.value[field]
  
  switch (field) {
    case 'username':
      if (!value) {
        newErrors.username = '用户名不能为空'
      } else if (value.length < 3 || value.length > 20) {
        newErrors.username = '用户名长度必须在3-20个字符之间'
      } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
        newErrors.username = '用户名只能包含字母、数字和下划线'
      } else {
        delete newErrors.username
      }
      break
      
    case 'password':
      if (!value) {
        newErrors.password = '密码不能为空'
      } else if (value.length < 6 || value.length > 20) {
        newErrors.password = '密码长度必须在6-20个字符之间'
      } else {
        delete newErrors.password
      }
      break
      
    case 'realName':
      if (!value) {
        newErrors.realName = '真实姓名不能为空'
      } else if (value.length > 50) {
        newErrors.realName = '真实姓名长度不能超过50个字符'
      } else {
        delete newErrors.realName
      }
      break
      
    case 'phone':
      if (!value) {
        newErrors.phone = '手机号不能为空'
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        newErrors.phone = '手机号格式不正确'
      } else {
        delete newErrors.phone
      }
      break
      
    case 'idCard':
      if (!value) {
        newErrors.idCard = '身份证号不能为空'
      } else if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/.test(value)) {
        newErrors.idCard = '身份证号格式不正确'
      } else {
        delete newErrors.idCard
      }
      break
      
    case 'email':
     if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        newErrors.email = '邮箱格式不正确'
      } else {
        delete newErrors.email
      }
      break
  }
  
  errors.value = newErrors
}

//注册
const handleRegister = async() => { 
  // 验证表单
  if (!validateRegisterForm()) {
    ElMessage.error('请修复表单中的错误')
    return
  }
  const result = await farmerRegisterApi(registerForm.value);
  if(result.code==200){
  ElMessage.success("注册成功");
  router.push('/farmer')
  }else{
    //提示信息
    ElMessage.error(result.message);
  }
}

const switchToRegister = () => {
  isRegistering.value = true
}
</script>

<style scoped>
/* 表单检验样式 */
.error-message {
  color: #f56565;
  font-size: 0.875rem;
  margin-top: 5px;
  font-weight: 500;
}

/* 添加表单组错误状态样式 */
.form-group.error input {
  border-color: #f56565 !important;
}

.form-group.error label {
  color: #f56565 !important;
}

/* 添加返回按钮样式 */
.back-home-btn {
  position: absolute;
  top: 20px;
  left: 20px;
  background: rgba(255, 255, 255, 0.9);
  border: 2px solid #4caf50;
  color: #4caf50;
  padding: 10px 15px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
  z-index: 1000;
}

.back-home-btn:hover {
  background: #4caf50;
  color: white;
  transform: translateX(-5px);
}

.btn-icon {
  font-size: 16px;
  font-weight: bold;
}
/* 公共登录样式 */
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.platform-title {
  font-size: 2.2rem;
  font-weight: 700;
  color: #2e7d32;
  margin-bottom: 10px;
}

.role-title {
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.welcome-text {
  font-size: 1.1rem;
  color: #666;
}

.login-form-container {
  background: white;
  padding: 40px;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 420px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin: 0 auto 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
}

.avatar .icon {
  font-size: 2.5rem;
}

.form-header h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.role-description {
  font-size: 0.9rem;
  color: #666;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #4caf50;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  font-size: 0.9rem;
}

.remember-me {
  display: flex;
  align-items: center;
  color: #666;
}

.remember-me input {
  margin-right: 5px;
}

.forgot-password {
  color: #4caf50;
  text-decoration: none;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-btn {
  width: 100%;
  padding: 14px;
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.register-link a {
  color: #4caf50;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

.register-form {
  margin-top: 20px;
}

.register-btn {
  width: 100%;
  padding: 14px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #666, #888);
  color: white;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.back-to-login {
  text-align: center;
  margin-top: 15px;
}

.back-to-login a {
  color: #666;
  text-decoration: none;
}

.back-to-login a:hover {
  text-decoration: underline;
}

.login-footer {
  text-align: center;
  margin-top: 30px;
  color: #666;
  font-size: 0.9rem;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-form-container {
    padding: 30px 20px;
    margin: 0 10px;
  }
  
  .platform-title {
    font-size: 1.8rem;
  }
  
  .role-title {
    font-size: 1.5rem;
  }
}

.farmer-login {
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
}

.farmer-avatar {
  background: linear-gradient(135deg, #4caf50, #81c784);
}

.farmer-btn {
  background: linear-gradient(135deg, #4caf50, #66bb6a);
}

.farmer-btn:hover {
  background: linear-gradient(135deg, #43a047, #5cb860);
}
</style>